import router from '../router/index'
import vue from 'vue'
import { getToken,removeToken } from '@/utils/auth'
import { API_BASE_URL } from '@/config'
import axios from 'axios'


export const _axios = axios.create({
  timeout: 300000, // 请求超时时间
  // withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})

// 创建axios实例
const service = axios.create({
  baseURL: API_BASE_URL, // api的base_url
  timeout: 300000 // 请求超时时间
})

// console.log("base: " + API_BASE_URL)


// request拦截器
service.interceptors.request.use(
  config => {
      // if (config.method === 'post') {
      //     config.data = qs.stringify(config.data);
      // }
      let token = getToken();
      if (token && token !== undefined && token !== "" && token !== "undefined") {
          config.headers['Authorization'] = "Bearer " + token;
      }

      return config;
  },
  error => {
      // Indicator.close()
      // Do something with request error
      Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
      const res = response.data;
      // console.log(res)

      if(res.code != 200) {
          if(res.code == "401") {
            removeToken();
            window.requestMessageError && window.requestMessageError.close()
            window.requestMessageError = vue.prototype.$message.error('请重新登录')
            router.push({ path: '/login/signin' })
            return Promise.reject(res);
          } else {
            window.requestMessageError && window.requestMessageError.close()
            window.requestMessageError = vue.prototype.$message.error(res.message)
            return Promise.reject(res);
            return res;

          }
      } else {
          return res;
      }
  },
  error => {
      window.requestMessageError && window.requestMessageError.close()
      // Toast(error.message);
      console.log(error,'##################')
      return Promise.reject(error);
  }
);

export default service;